package com.easyj.base.security.service;

import java.util.Calendar;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.easyj.admin.db.model.User;
import com.easyj.admin.sys.service.UserService;
import com.easyj.base.security.SecurityConstant;
import com.easyj.base.security.SimpleUser;
import com.easyj.base.security.UserAuthorities;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
	
	@Autowired
	private  UserService userService;
	
	@Autowired
	private HttpServletRequest request;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User user=userService.findByLoginName(username); //sql:status=1
		if(user==null) {
			throw new UsernameNotFoundException("用户不存在");
		}
		//计算，连续输错密码，账号将暂时锁定------------
		boolean locked=false;
		Integer errCount=(user.getLoginErrCount()==null?0:user.getLoginErrCount());
		if(user.getLoginTime()!=null){
			Calendar cal=Calendar.getInstance();
			Date now=cal.getTime();
		
			cal.setTime(user.getLoginTime());
			cal.add(Calendar.HOUR_OF_DAY, SecurityConstant.LockHour);
			Date diff=cal.getTime();
			
			if(now.after(diff)){ //超过锁定时间，清零
				errCount=0;
			}else {
				if(errCount>=SecurityConstant.Max_ErrCount){
					locked=true;
				}
			}
		}
		
		 //放到 request ,后继处理
		request.setAttribute("user_id", user.getId());
		request.setAttribute("login_errcount", errCount);
		
		//get and put permissions to cache!
		UserAuthorities  permissions=userService.getUserAuthorities(user.getId(),user.getDepartmentId());
		
		
		//username=user.getLoginName(),user.getPassword() 用于登录校验密码 
		SimpleUser details=new  SimpleUser(user.getId(),user.getDepartmentId(),user.getName(),user.getLoginName(),user.getPassword(),true,locked,permissions.getAuthorities());
		return details;
	}
}
